package cn.mumzone.pos.ui.fragment;

import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.adapter.rv.MultiItemTypeAdapter;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.loading.dialog.LoadingDialog;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.SPManager;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.BuildConfig;
import cn.mumzone.pos.R;
import cn.mumzone.pos.model.CashServiceResult;
import cn.mumzone.pos.model.PopupHintEntity;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.presenter.CashServicePresenter;
import cn.mumzone.pos.presenter.contract.CashServiceContract;
import cn.mumzone.pos.ui.activity.ACT_InventoryDetail;
import cn.mumzone.pos.ui.activity.ACT_Redeem;
import cn.mumzone.pos.ui.adapter.ADA_CashServiceList;
import cn.mumzone.pos.ui.activity.ACT_OpenOrder;
import cn.mumzone.pos.ui.activity.ACT_ReserveDetail;
import cn.mumzone.pos.ui.widgets.PosRefreshHeader;
import cn.mumzone.pos.ui.widgets.others.StoreHouseHeader;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.constant.RefreshState;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshLoadMoreListener;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.PopupUtil;

/**
 * Created by JoeLjt on 2019/6/13.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class FRA_CashService extends BaseFragment<CashServicePresenter> implements CashServiceContract.View {


    public static final String STATUS_RESERVE = "0";
    public static final String STATUS_SERVICE_RESERVE = "1";
    public static final String STATUS_SERVICE_BABY_SWIM = "4";
    public static final String STATUS_CLOSED = "3";

    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.et_search_cash)
    EditText etSearchCash;
    @BindView(R.id.tv_open_order)
    TextView tvOpenOrder;
    @BindView(R.id.rl_refresh)
    SmartRefreshLayout rlRefresh;
    @BindView(R.id.cash_reserve_list)
    LRecyclerView rvReserveList;
    @BindView(R.id.tv_reserve)
    TextView tvReserve;
    @BindView(R.id.tv_service)
    TextView tvService;
    @BindView(R.id.tv_close)
    TextView tvClose;
    @BindView(R.id.iv_clear_input)
    ImageView ivClearInput;
    @BindView(R.id.tv_status_reserve)
    TextView tvStatusReserve;
    @BindView(R.id.tv_status_service)
    TextView tvStatusService;
    @BindView(R.id.tv_status_close)
    TextView tvStatusClose;
    @BindView(R.id.tv_push_tip)
    TextView tvJPushTip;
    @BindView(R.id.ll_empty_layout)
    LinearLayout llEmptyLayout;
    @BindView(R.id.iv_message_icon)
    ImageView ivMessageIcon;
    @BindView(R.id.tv_message)
    TextView tvMessage;
    @BindView(R.id.tv_message_info)
    TextView tvMessageInfo;
    @BindView(R.id.tv_go_open_order)
    TextView tvGoOpenOrder;
    @BindView(R.id.ll_cash_service_target)
    LinearLayout llTarget;

    @BindView(R.id.ll_reserve)
    LinearLayout llReserve;
    @BindView(R.id.iv_refresh)
    AppCompatImageView ivRefresh;

    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private ADA_CashServiceList mDataAdapter;

    boolean selectReserve = true;
    boolean selectService = true;
    boolean selectClose = true;
    boolean isScanExecuted = true;

    private ArrayList<PopupWindow> mPopupHintList;

    private PopupWindow mOpenOrderPopup;
    private PopupWindow mReserveHintPopup;
    private PopupWindow mRefreshOrderPopup;

    @Override
    protected void onUserVisible() {

        refreshToInitial();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            if (mPopupHintList != null) {
                for (PopupWindow popupWindow : mPopupHintList) {
                    if (popupWindow != null) {
                        popupWindow.dismiss();
                    }
                }
                mPopupHintList.clear();
                mPopupHintList = null;
            }
        }
    }

    @Override
    protected void initEventAndData() {

        initReserveList();

        initRefreshView();

        initSearchView();
        mPresenter.setStatus(getReserveStatus());
//        rlRefresh.autoRefresh();

        showEmptyView(true, true);
        refreshStatusCheck();

        mPresenter.initEvent();
        etScan.setInputType(InputType.TYPE_NULL);
        etScan.requestFocus();
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearchCash, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.searchByScan("FW" + code);
                    }
                    etScan.setText("");
                    isScanExecuted = true;
                }
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearchCash.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
            }
        });

        etScan.postDelayed(new Runnable() {
            @Override
            public void run() {
                showPopupHint();
                isPopupHintPrepared = true;
            }
        }, 800);

    }

    private void initSearchView() {
        etSearchCash.addTextChangedListener(new TextWatcherAdapter() {

            @Override
            public void afterTextChanged(Editable editable) {
                super.afterTextChanged(editable);
                String keyWord = editable.toString();
                ivClearInput.setVisibility(StringUtils.isEmpty(keyWord) ? View.GONE : View.VISIBLE);
                mDataAdapter.clear();
                mPresenter.refreshAppointmentListWithKeyWord(keyWord);
            }
        });
    }

    private void initRefreshView() {
        rlRefresh.setEnableRefresh(true);
        rlRefresh.setEnableLoadMore(false);
        rlRefresh.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (tvJPushTip != null) tvJPushTip.setVisibility(View.GONE);
                rvReserveList.setClickable(false);
                mPresenter.refreshAppointmentList();
            }
        });
    }

    private void initReserveList() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 4);
        rvReserveList.setLayoutManager(manager);
        mDataAdapter = new ADA_CashServiceList(mContext);
        mDataAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(position == -1){
                    return;
                }
                ReserveOrderEntity entity = mDataAdapter.getDataList().get(position - 1);

                //按状态跳转详情页
                switch (entity.getStatus()) {
                    case ReserveOrderEntity.ORDER_STATUS_CLOSED://关闭状态跳转预约详情
                        ACT_ReserveDetail.startAc(mContext, entity);
                        break;
                    case ReserveOrderEntity.ORDER_STATUS_RESERVED://预约状态跳转开单页面
                        ACT_OpenOrder.startAc(mContext, entity);
                        break;
                    case ReserveOrderEntity.ORDER_STATUS_ARRIVED://产康-服务中跳转开单
                        ACT_OpenOrder.startAc(mContext, entity);
                        break;
                    case ReserveOrderEntity.ORDER_STATUS_PROCESSING://小儿游泳-服务中跳转预约详情
                        ACT_ReserveDetail.startAc(mContext, entity);
                        break;
                }

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        rvReserveList.setAdapter(mLRecyclerViewAdapter);
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_8)
                .setColorResource(android.R.color.transparent)
                .build();
        rvReserveList.addItemDecoration(divider);
        rvReserveList.setHasFixedSize(true);
        rvReserveList.setPullRefreshEnabled(false);
        rvReserveList.setLoadMoreEnabled(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_cash_service;
    }

    @OnClick({R.id.tv_open_order, R.id.ll_reserve, R.id.ll_service, R.id.ll_close, R.id.iv_refresh,
            R.id.iv_clear_input, R.id.tv_go_open_order, R.id.tv_cash_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_open_order:
                PopupUtil.dismissPopup(PopupUtil.CASH_OPEN_ORDER, mOpenOrderPopup);
                ACT_OpenOrder.startAc(mContext);
                break;
            case R.id.ll_reserve:
                PopupUtil.dismissPopup(PopupUtil.CASH_RESERVE, mReserveHintPopup);
                if (rlRefresh.getState() != RefreshState.None) {
                    return;
                }
                mDataAdapter.clear();
                selectReserve = !selectReserve;
                refreshStatusCheck();
                mPresenter.setStatus(getReserveStatus());
                rlRefresh.autoRefresh();
                break;
            case R.id.ll_service:
                if (rlRefresh.getState() != RefreshState.None) {
                    return;
                }
                mDataAdapter.clear();
                selectService = !selectService;
                refreshStatusCheck();
                mPresenter.setStatus(getReserveStatus());
                rlRefresh.autoRefresh();
                break;
            case R.id.ll_close:
                if (rlRefresh.getState() != RefreshState.None) {
                    return;
                }
                selectClose = !selectClose;
                mDataAdapter.clear();
                refreshStatusCheck();
                mPresenter.setStatus(getReserveStatus());
                rlRefresh.autoRefresh();
                break;
            case R.id.iv_refresh:
                PopupUtil.dismissPopup(PopupUtil.CASH_REFRESH, mRefreshOrderPopup);
                if (rlRefresh.getState() != RefreshState.None) {
                    return;
                }
                etSearchCash.clearFocus();
                etScan.requestFocus();
                mDataAdapter.clear();
                refreshToInitial();
                break;
            case R.id.iv_clear_input:
                refreshToInitial();
                etSearchCash.setText("");
                etSearchCash.clearFocus();
                etScan.requestFocus();
                EditTextUtil.hideSoftInput(mContext, etSearchCash);
                break;
            case R.id.tv_go_open_order:
                ACT_OpenOrder.startAc(mContext);
                break;
            case R.id.tv_cash_title:
                if (BuildConfig.DEBUG) {
//                    ACT_InventoryDetail.startAc(mContext, "b5a1a20716d4445d9163b0cd2c5fa527");
//                    GoodsUtil.showCheckGoodsInventoryResultDialog(mContext,"商品1" +"\n"+"商品2");
                }
                break;
        }
    }

    public void refreshToInitial() {
        selectReserve = true;
        selectService = true;
        selectClose = true;
        refreshStatusCheck();
        mPresenter.setStatus(getReserveStatus());
        rlRefresh.autoRefresh();
        etSearchCash.clearFocus();
        etScan.requestFocus();
    }


    private void refreshStatusCheck() {

        if (selectReserve) {
            tvStatusReserve.setBackgroundResource(R.drawable.shape_floating_bar_reserve);
        } else {
            tvStatusReserve.setBackgroundResource(R.drawable.shape_floating_bar_un_select);
        }
        tvReserve.setTextColor(getResources().getColor(selectReserve ? R.color.white_color : R.color.order_status_unable));


        if (selectService) {
            tvStatusService.setBackgroundResource(R.drawable.shape_floating_bar_service);
        } else {
            tvStatusService.setBackgroundResource(R.drawable.shape_floating_bar_un_select);

        }
        tvService.setTextColor(getResources().getColor(selectService ? R.color.white_color : R.color.order_status_unable));


        if (selectClose) {
            tvStatusClose.setBackgroundResource(R.drawable.shape_floating_bar_close);
        } else {
            tvStatusClose.setBackgroundResource(R.drawable.shape_floating_bar_un_select);
        }
        tvClose.setTextColor(getResources().getColor(selectClose ? R.color.white_color : R.color.order_status_unable));


    }

    /**
     * 获取选中预约状态
     *
     * @return
     */
    private String getReserveStatus() {
        StringBuilder builder = new StringBuilder();
        if (selectReserve) {
            builder.append(STATUS_RESERVE);
        }
        if (selectService) {
            if (selectReserve) {
                builder.append(",");
            }
            if (AppUtil.hasServiceBusiness()) {
                builder.append(STATUS_SERVICE_RESERVE);
            } else {
                builder.append(STATUS_SERVICE_BABY_SWIM);
            }
        }
        if (selectClose) {
            if (selectReserve || selectService) {
                builder.append(",");
            }
            builder.append(STATUS_CLOSED);
        }
        if(!selectReserve && !selectService && !selectClose){
            builder.append(STATUS_RESERVE).append(",");
            if (AppUtil.hasServiceBusiness()) {
                builder.append(STATUS_SERVICE_RESERVE);
            } else {
                builder.append(STATUS_SERVICE_BABY_SWIM);
            }
            builder.append(",").append(STATUS_CLOSED);
        }
        return builder.toString();
    }

    @Override
    public void showError(String msg) {
        rvReserveList.setClickable(true);
        isScanExecuted = false;
        etScan.requestFocus();
        super.showError(msg);
        rlRefresh.finishRefresh();
        rlRefresh.finishLoadMore();
    }

    @Override
    public synchronized void showAppointmentInfo(CashServiceResult result) {
        isScanExecuted = false;
        rvReserveList.setClickable(true);
        etScan.requestFocus();
        rlRefresh.finishRefresh();
        rlRefresh.finishLoadMore();
        tvReserve.setText(StringUtils.isMoreThenZero(result.getReservationNum()) ?
                String.format("已预约(%s)", result.getReservationNum()) : "已预约");
        tvService.setText(StringUtils.isMoreThenZero(result.getInServiceNum()) ?
                String.format("服务中(%s)", result.getInServiceNum()) : "服务中");
        tvClose.setText(StringUtils.isMoreThenZero(result.getClosedNum()) ?
                String.format("已关闭(%s)", result.getClosedNum()) : "已关闭");

        if (!ListUtil.isListEmpty(result.getList())) {
            showEmptyView(false, false);
            mDataAdapter.update(result.getList(), true);
            mLRecyclerViewAdapter.notifyDataSetChanged();

        } else {
            showEmptyView(true, StringUtils.isEmpty(etSearchCash.getText().toString().trim()));
        }

    }

    public void showEmptyView(boolean isEmpty, boolean isDataEmpty) {
        if (isEmpty) {
            llEmptyLayout.setVisibility(View.VISIBLE);
            ivMessageIcon.setImageResource(isDataEmpty ? R.mipmap.ic_cash_service_empty : R.mipmap.ic_cash_service_empty_search);
            tvMessage.setText(isDataEmpty ? "暂无服务单" : "没有找到任何内容");
            tvMessageInfo.setText(isDataEmpty ? "美好的一天，从开启第一单开始~" : "你可以换个关键词试试~");
            tvGoOpenOrder.setVisibility(isDataEmpty ? View.VISIBLE : View.GONE);
        } else {
            llEmptyLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showJPushView() {
        tvJPushTip.setVisibility(View.VISIBLE);
    }

    @Override
    protected View getTargetView() {
        return llTarget;
    }

    @Override
    protected boolean hasViewPermission() {
        return AppConstants.TEMP_USER_PERMISSION != null && AppConstants.TEMP_USER_PERMISSION.isCashierDesk();
    }

    @Override
    public boolean hasPopupHint() {
        return true;
    }

    @Override
    public void hidePopupHint() {
        if (mPopupHintList != null) {
            for (PopupWindow popupWindow : mPopupHintList) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
            mPopupHintList.clear();
            mPopupHintList = null;
        }
    }

    @Override
    public void showPopupHint() {
        mPopupHintList = new ArrayList<>();

        mOpenOrderPopup = PopupUtil.showBlackBgPopup(tvOpenOrder,
                PopupUtil.CASH_OPEN_ORDER, "点击开始售卖或下服务订单", PopupUtil.LEFT);

        mReserveHintPopup = PopupUtil.showBlackBgPopup(llReserve,
                PopupUtil.CASH_RESERVE, "点击可隐藏订单状态", PopupUtil.LEFT_TOP);

        mRefreshOrderPopup = PopupUtil.showBlackBgPopup(ivRefresh,
                PopupUtil.CASH_REFRESH, "您有新的订单，点击刷新", PopupUtil.LEFT_TOP);

        mPopupHintList.add(mOpenOrderPopup);
        mPopupHintList.add(mReserveHintPopup);
        mPopupHintList.add(mRefreshOrderPopup);

//        tvOpenOrder.post(new Runnable() {
//            @Override
//            public void run() {
//                if (mPopupHintList != null) {
//
//                    mOpenOrderPopup = PopupUtil.showBlackBgPopup(tvOpenOrder,
//                            PopupUtil.CASH_OPEN_ORDER, "点击开始售卖或下服务订单", PopupUtil.LEFT);
//
//                    mReserveHintPopup = PopupUtil.showBlackBgPopup(llReserve,
//                            PopupUtil.CASH_RESERVE, "点击可隐藏订单状态", PopupUtil.LEFT_TOP);
//
//                    mRefreshOrderPopup = PopupUtil.showBlackBgPopup(ivRefresh,
//                            PopupUtil.CASH_REFRESH, "您有新的订单，点击刷新", PopupUtil.LEFT_TOP);
//
//                    mPopupHintList.add(mOpenOrderPopup);
//                    mPopupHintList.add(mReserveHintPopup);
//                    mPopupHintList.add(mRefreshOrderPopup);
//
//                }
//            }
//        });


    }

}
